import { defineStore } from "pinia";
import { ref } from "vue";
import type { Ref } from "vue";
import type { LoginParams, UserInfo } from "@/types/userTypes/userTypes.ts";
import type { userStoreInterface } from "@/pinia/modules/userStore/interface.ts";
import { qqBindMobileAPI, qqBindSendCodeAPI, sendCodeAPI, userMobileLoginAPI, userNameLoginAPI, userQQLoginAPI } from "@/api/useApi/userApi.ts";
import { getUserInfo, removeUserInfo, setUserInfo } from "@/utils/localStorage.ts";

const useUserStore = defineStore("useStore", (): userStoreInterface => {
   const userInfo: Ref<UserInfo> = ref<UserInfo>(<UserInfo>getUserInfo() || {} as UserInfo);
   const userNameLogin = async (data: LoginParams): Promise<string> => {
      const { result }: { result: UserInfo } = await userNameLoginAPI(data);
      userInfo.value = result;
      setUserInfo<UserInfo>(result);
      return "账号登录成功";
   };

   const sendCode = async (mobile: string): Promise<string> => {
      const { result } = await sendCodeAPI(mobile);
      return "123456";
   };

   const qqBindSendCode = async (mobile: string): Promise<string> => {
      const { result } = await qqBindSendCodeAPI(mobile);
      return "123456";
   };

   const userMobileLogin = async (data: LoginParams): Promise<string> => {
      const { result }: { result: UserInfo } = await userMobileLoginAPI(data);
      userInfo.value = result;
      setUserInfo<UserInfo>(result);
      return "手机号登录成功";
   };

   const userQQLogin = async (unionId: string, source: number): Promise<string> => {
      const { result }: { result: UserInfo } = await userQQLoginAPI(unionId, source);
      userInfo.value = result;
      setUserInfo<UserInfo>(result);
      return "QQ号登录成功";
   };

   const qqBindMobile = async (mobile: string, code: string, unionId: string): Promise<string> => {
      const { result }: { result: UserInfo } = await qqBindMobileAPI(mobile, code, unionId);
      userInfo.value = result;
      setUserInfo<UserInfo>(result);
      return "手机号绑定成功";
   };

   const logout = async (): Promise<string> => {
      removeUserInfo();
      userInfo.value = {} as UserInfo;
      return "退出成功";
   };

   return {
      userInfo,
      userNameLogin,
      sendCode,
      qqBindSendCode,
      userMobileLogin,
      userQQLogin,
      qqBindMobile,
      logout,
   };
});


export default useUserStore;
